﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Common;
using System.Net;

namespace CSGame
{
	public class ClientTerminal
	{
		Socket m_socClient;
		private SocketListener m_listener;

		public event TCPTerminal_MessageRecivedDel MessageRecived;
		public event TCPTerminal_ConnectDel Connected;
		public event TCPTerminal_DisconnectDel Disconncted;

		public void Connect(IPAddress remoteIPAddress, int alPort)
		{
			m_socClient = new Socket(AddressFamily.InterNetwork,
				SocketType.Stream, ProtocolType.Tcp);

			IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, alPort);

			m_socClient.Connect(remoteEndPoint);

			OnServerConnection();
		}

		public void SendMessage(byte[] buffer)
		{
			if (m_socClient == null)
			{
				return;
			}
			m_socClient.Send(buffer);

		}

		public void StartListen()
		{
			if (m_socClient == null)
			{
				return;
			}

			if (m_listener != null)
			{
				return;
			}

			m_listener = new SocketListener();
			m_listener.Disconnected += OnServerConnectionDroped;
			m_listener.MessageRecived += OnMessageRecvied;

			m_listener.StartReciving(m_socClient);
		}

		public void Close()
		{
			if (m_socClient == null)
			{
				return;
			}

			if (m_listener != null)
			{
				m_listener.StopListening();
			}

			m_socClient.Close();
			m_listener = null;
			m_socClient = null;
		}

		private void OnServerConnection()
		{
			if (Connected != null)
			{
				Connected(m_socClient);
			}
		}

		private void OnMessageRecvied(Socket socket, byte[] buffer)
		{
			if (MessageRecived != null)
			{
				MessageRecived(socket, buffer);
			}
		}

		private void OnServerConnectionDroped(Socket socket)
		{
			Close();
			RaiseServerDisconnected(socket);
		}

		private void RaiseServerDisconnected(Socket socket)
		{
			if (Disconncted != null)
			{
				Disconncted(socket);
			}
		}
	}
}
